package main

import (
	"fmt"
	"time"
)

/*
  状态模式
  把对象每一个状态的行为封装在对象内部。避免大量状态逻辑杂糅。
  例子： 游戏状态
*/

type State interface {
	Next() State
	Update()
}
//开始状态
type GameStart struct {
}

func (g GameStart) Next() State {
	fmt.Println("start next")
	return new(GameRun)
}
func (g GameStart) Update()  {
	fmt.Println("game start")
}
//运行状态
type GameRun struct {

}
func (g GameRun) Next() State {
	fmt.Println("run next")
	return new(GameEnd)
}
func (g GameRun) Update()  {
	fmt.Println("game run")
}
//结束状态
type GameEnd struct {
}

func (g GameEnd) Next() State {
	fmt.Println("end next")
	return new(GameStart)
}
func (g GameEnd) Update()  {
	fmt.Println("game end")
}


func main() {

	state := &GameStart{}
	ch := make(chan string)

	go func(state State,ch chan string) {
		for  {
			select {
			case s := <- ch:
				if s == "next" {
					state = state.Next()
				}else if s == "stop"{
					return
				}
			default:
				state.Update()
			}
		}
	}(state,ch)

	ch <- "start"
	time.Sleep(1000)
	ch <- "next"
	time.Sleep(1000)
	ch <- "next"
	time.Sleep(1000)
	ch <- "stop"
}
